package org.babygo.connect.handler.code;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

import org.babygo.connect.client.NettyClient;
import org.babygo.connect.protocol.GetAndSendFileRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

public class EncodeOutHandler extends ChannelOutboundHandlerAdapter{
	private Logger log = LoggerFactory.getLogger(NettyClient.class);

	@Override
	public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
		log.info("doEncode");
		try{
			ByteBuf m = null;
			if (msg instanceof GetAndSendFileRequest){
				GetAndSendFileRequest fileRequest = (GetAndSendFileRequest)msg;
				fileRequest.setFile(null);
				byte[] bytes =new String(JSON.toJSONString(fileRequest) + "\n").getBytes();
				m = Unpooled.buffer(128);
				m.writeBytes(bytes);
				ctx.writeAndFlush(m);
			}
		} catch(Exception e){
			log.error("序列化异常", e);
		}
	}
}